package com.seeyon.ctp.rest.resources;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.seeyon.apps.collaboration.manager.ColManager;
import com.seeyon.apps.collaboration.po.ColSummary;
import com.seeyon.apps.gkcwplugin.dao.DealDataDao;
import com.seeyon.apps.gkcwplugin.po.ChailfBankPO;
import com.seeyon.apps.gkcwplugin.po.FapiaoKjBankPO;
import com.seeyon.apps.gkcwplugin.po.FapiaoRzPO;
import com.seeyon.apps.gkcwplugin.po.FukuanBankPO;
import com.seeyon.apps.gkcwplugin.po.HetongBankPO;
import com.seeyon.apps.gkcwplugin.po.NeibuZjBankPO;
import com.seeyon.apps.gkcwplugin.po.ZiJinRZPO;
import com.seeyon.apps.gkcwplugin.util.HttpKit;
import com.seeyon.apps.gkcwplugin.util.JsonKit;
import com.seeyon.apps.yxxt.dao.Formmain53375Dao;
import com.seeyon.apps.yxxt.po.Formmain5337;
import com.seeyon.apps.yxxt.util.JDBCUtil;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.config.PerformanceConfig;
import com.seeyon.ctp.common.config.SystemConfig;
import com.seeyon.ctp.common.constants.ApplicationCategoryEnum;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.filemanager.manager.AttachmentManager;
import com.seeyon.ctp.common.filemanager.manager.FileManager;
import com.seeyon.ctp.common.office.trans.util.OfficeTransHelper;
import com.seeyon.ctp.common.po.filemanager.Attachment;
import com.seeyon.ctp.common.po.filemanager.V3XFile;
import com.seeyon.ctp.util.DBAgent;
import com.seeyon.ctp.util.EnumUtil;
import com.seeyon.ctp.util.JDBCAgent;
import com.seeyon.ctp.util.UUIDLong;
import com.seeyon.ctp.util.annotation.RestInterfaceAnnotation;
import com.seeyon.ctp.util.json.JSONUtil;

@Path("image")
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces(MediaType.APPLICATION_JSON)
public class YxxtResource extends BaseResource {
    static final Log log = LogFactory.getLog(YxxtResource.class);
    private Formmain53375Dao formmain5337Dao = (Formmain53375Dao) AppContext.getBean("formmain5337Dao");
    private DealDataDao dealDataDao = (DealDataDao) AppContext.getBean("dealDataDao");
    private ColManager colManager = (ColManager) AppContext.getBean("colManager");
    @Context
    private HttpServletRequest request;

    @Context
    private HttpServletResponse response;

    private AttachmentManager attachmentManager;
    private FileManager fileManager;
    private SystemConfig systemConfig;
    
 // REST地址
 	private String restUrl = AppContext.getSystemProperty("gkcwplugin.restUrl");
 	// REST用户登录名
 	private String userName = AppContext.getSystemProperty("gkcwplugin.restName");
 	// REST用户密码
 	private String password = AppContext.getSystemProperty("gkcwplugin.restPassword");
 	// 表单发送人员
 	private String loginName = AppContext.getSystemProperty("gkcwplugin.senderMember");

    @POST
    @Path("imageState")
    @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public Response imageUrl(Map<String, String> params) throws UnsupportedEncodingException {
        String url = "http://114.218.158.106:8801";
//        String url = "http://127.0.0.1";
        String voucherId = params.get("voucherId");
        String state = params.get("state");
        String sql = "select ID,field0001,field0002 from formmain_5337 where field0002= '" + voucherId + "'";
        List<Map> resList = JDBCUtil.doQuery(sql);
        if ("add".equals(state)) {
            if (resList.size() <= 0) {
                Formmain5337 formmain5337 = new Formmain5337();
                formmain5337.setField0002(voucherId);
                formmain5337.setID(UUIDLong.longUUID());
                formmain5337.setCreateTime(new Date());
                formmain5337Dao.insertFormmain5337(formmain5337);
                log.info("----------------------新增数据的id=" + formmain5337.getID());
                log.info("----------------------新增数据的voucherId=" + voucherId);
//				sql = "select ID,field0001,field0002 from formmain_5337 where field0002= " + voucherId;
//				resList = JDBCUtil.doQuery(sql);
//				String id = String.valueOf(resList.get(0).get("id"));
                // http://127.0.0.1/seeyon/cap4/businessTemplateController.do?method=formContent&type=edit&rightId=9221419312382495186.-5634232621113981852&moduleId=-7620855170988228382&formTemplateId=-330010406509917111&viewConditionId=&columnId=-330010406509917111&moduleType=42
                url = url + "/seeyon/login/sso?from=sample&ticket=c2VleW9uZms=&tourl=" + URLEncoder.encode(
                        "/seeyon/cap4/businessTemplateController.do?method=formContent&type=edit&rightId=7619147149644941021.-5614821574638090007&moduleId="
                                + formmain5337.getID()
                                + "&formTemplateId=-629788579583865877&viewConditionId=&columnId=-629788579583865877&moduleType=42&btnId=8573520930179925861&tplId=850010",
                        "UTF-8");
            } else {
                String id = String.valueOf(resList.get(0).get("id"));
                // http://127.0.0.1/seeyon/cap4/businessTemplateController.do?method=formContent&type=edit&rightId=9221419312382495186.-5634232621113981852&moduleId=-7620855170988228382&formTemplateId=-330010406509917111&viewConditionId=&columnId=-330010406509917111&moduleType=42
                url = url + "/seeyon/login/sso?from=sample&ticket=c2VleW9uZms=&tourl=" + URLEncoder.encode(
                        "/seeyon/cap4/businessTemplateController.do?method=formContent&type=edit&rightId=7619147149644941021.-5614821574638090007&moduleId="
                                + id
                                + "&formTemplateId=-629788579583865877&viewConditionId=&columnId=-629788579583865877&moduleType=42&btnId=8573520930179925861&tplId=850010",
                        "UTF-8");
            }
            return success(url);
        } else if ("update".equals(state)) {
            if (resList.size() > 0) {
                String id = String.valueOf(resList.get(0).get("id"));
                // http://127.0.0.1/seeyon/cap4/businessTemplateController.do?method=formContent&type=edit&rightId=9221419312382495186.-5634232621113981852&moduleId=-7620855170988228382&formTemplateId=-330010406509917111&viewConditionId=&columnId=-330010406509917111&moduleType=42
                url = url + "/seeyon/login/sso?from=sample&ticket=c2VleW9uZms=&tourl=" + URLEncoder.encode(
                        "/seeyon/cap4/businessTemplateController.do?method=formContent&type=edit&rightId=7619147149644941021.-5614821574638090007&moduleId="
                                + id
                                + "&formTemplateId=-629788579583865877&viewConditionId=&columnId=-629788579583865877&moduleType=42&btnId=8573520930179925861&tplId=850010",
                        "UTF-8");
            }
            return success(url);
        } else if ("view".equals(state)) {
            if (resList.size() > 0) {
                String id = String.valueOf(resList.get(0).get("id"));
                // http://127.0.0.1/seeyon/cap4/businessTemplateController.do?method=formContent&type=browse&rightId=9221419312382495186.4972216218221104129&moduleId=-7620855170988228382&formTemplateId=-330010406509917111&viewConditionId=&columnId=-330010406509917111&moduleType=42&conditionIdDeal=
                url = url + "/seeyon/login/sso?from=sample&ticket=c2VleW9uZms=&tourl=" + URLEncoder.encode(
                        "/seeyon/cap4/businessTemplateController.do?method=formContent&type=browse&rightId=7619147149644941021.-2719020395609633668&moduleId="
                                + id
                                + "&formTemplateId=-629788579583865877&viewConditionId=&columnId=-629788579583865877&moduleType=42&conditionIdDeal=&needUpdate=1&tplId=850010",
                        "UTF-8");
//                url = url + "/seeyon/cap4/businessTemplateController.do?method=formContent&type=browse&rightId=9221419312382495186.4972216218221104129&moduleId=" + id + "&formTemplateId=-330010406509917111&viewConditionId=&columnId=-330010406509917111&moduleType=42&conditionIdDeal=";
            }
            return success(url);
        } else {
            return success("");
        }
    }

	@POST
    @Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON})
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @RestInterfaceAnnotation
    @Path("upload")
    /**
     * 上传附件，参数同Web文件上传。
     *
     * @return 上传成功返回ok，否则返回错误信息
     * @throws BusinessException 
     * @throws NumberFormatException 
     */
    public Response upload() throws NumberFormatException, BusinessException {
    	String from = request.getParameter("from");
    	String billID = request.getParameter("billID");
    	String formType = request.getParameter("formType");
    	String voucherId = request.getParameter("voucherId");
    	
        String extensions = request.getParameter("extensions");
        String applicationCategory = request.getParameter("applicationCategory");
        String typeStr = request.getParameter("type");
        String maxSizeStr = request.getParameter("maxSize");
        String ucFlag = request.getParameter("ucFlag");
        String reference = request.getParameter("reference");
        String summaryId = "";

        com.seeyon.ctp.common.filemanager.Constants.ATTACHMENT_TYPE type = null;
        if (StringUtils.isNotBlank(typeStr)) {
            type = EnumUtil.getEnumByOrdinal(com.seeyon.ctp.common.filemanager.Constants.ATTACHMENT_TYPE.class,
                    Integer.valueOf(typeStr));
        } else {
            type = com.seeyon.ctp.common.filemanager.Constants.ATTACHMENT_TYPE.FILE;
        }

        ApplicationCategoryEnum category = null;
        if (StringUtils.isNotBlank(applicationCategory)) {
            category = ApplicationCategoryEnum.valueOf(Integer.valueOf(applicationCategory));
        } else {
            category = ApplicationCategoryEnum.global;
            log.warn("上传文件：v3x:fileUpload没有设定applicationCategory属性，将设置为‘全局’。");
        }

        long maxSize = 0L;
        // m3上传的文件大小走致信设置
        if ("yes".equals(ucFlag)) {
            maxSize = Long.parseLong(PerformanceConfig.getInstance().getConfig("zx.set.file.maxSize")) * 1024 * 1024;
        } else {
            maxSize = Long.parseLong(PerformanceConfig.getInstance().getConfig("fileUpload.maxSize")) * 1024 * 1024;
        }
        if (StringUtils.isNotBlank(maxSizeStr)) {
            maxSize = Long.valueOf(maxSizeStr);
        }
        String officeMobileAttach = getSystemConfig().get("office_mobile_attach");
        Map<String, V3XFile> v3xFiles = null;
        try {
            CommonsMultipartResolver resolver = (CommonsMultipartResolver) AppContext.getBean("multipartResolver");
            HttpServletRequest req = resolver.resolveMultipart(request);
            v3xFiles = getFileManager().uploadFiles(req, extensions, maxSize);

            if (v3xFiles != null) {
                long subReference = UUIDLong.longUUID();
                
                // 新增底表数据
                Formmain5337 formmain5337 = new Formmain5337();
                FukuanBankPO fkBankPO = new FukuanBankPO();
                ChailfBankPO clBankPO = new ChailfBankPO();
                HetongBankPO htBankPO = new HetongBankPO();
                NeibuZjBankPO nbzjBankPO = new NeibuZjBankPO();
                FapiaoKjBankPO fpKjBankPO = new FapiaoKjBankPO();
                JDBCAgent jdbc = new JDBCAgent();
                if ("1".equals(from)) {
                	formmain5337.setField0001(String.valueOf(subReference));
                    formmain5337.setField0002(voucherId);
                    formmain5337.setID(UUIDLong.longUUID());
                    formmain5337.setCreateTime(new Date());
                    formmain5337Dao.insertFormmain5337(formmain5337);
                } else if ("2".equals(from)) {
                	if ("1".equals(formType)) {
                		String sql = "UPDATE formson_5200 SET field0179 = ? WHERE id = ?";
            			List<Object> params = new ArrayList<>();
            			params.add(subReference);
            			params.add(billID);
            	        jdbc.execute(sql, params);
					} else if ("2".equals(formType)) {
						String sql = "UPDATE formson_5187 SET field0183 = ? WHERE id = ?";
            			List<Object> params = new ArrayList<>();
            			params.add(subReference);
            			params.add(billID);
            	        jdbc.execute(sql, params);
					} else if ("3".equals(formType)) {
						String sql = "UPDATE formson_5171 SET field0184 = ? WHERE id = ?";
            			List<Object> params = new ArrayList<>();
            			params.add(subReference);
            			params.add(billID);
            	        jdbc.execute(sql, params);
					} else if ("4".equals(formType)) {
						String sql = "UPDATE formson_5179 SET field0184 = ? WHERE id = ?";
            			List<Object> params = new ArrayList<>();
            			params.add(subReference);
            			params.add(billID);
            	        jdbc.execute(sql, params);
					} else if ("5".equals(formType)) {
					} else if ("6".equals(formType)) {
					} else if ("7".equals(formType)) {
					} else {
						log.error("表单类型错误，无法回填数据");
					}
                } else if ("3".equals(from)) {
                	if ("1".equals(formType)) {
                		fkBankPO = dealDataDao.findFukuanBankPOById(voucherId);
                		
                		if (fkBankPO != null) {
                			fkBankPO.setYhkd(String.valueOf(subReference));
                		} else {
                			List<FukuanBankPO> findFukuanBankPO = dealDataDao.findFukuanBankPO(Long.parseLong(billID));
                			for (FukuanBankPO row : findFukuanBankPO) {
                				DBAgent.delete(row);
                			}
                			
                			fkBankPO = new FukuanBankPO();
                			
                			fkBankPO.setId(UUIDLong.longUUID());
    						fkBankPO.setFormmainId(Long.parseLong(billID));
    						fkBankPO.setYhkd(String.valueOf(subReference));
    						fkBankPO.setPzh(voucherId);
                		}
        	        	
						dealDataDao.updateFukuanBankPOData(fkBankPO);
					} else if ("2".equals(formType)) {
						clBankPO = dealDataDao.findChailfBankPOById(voucherId);
						
						if (clBankPO != null) {
							clBankPO.setYhkd(String.valueOf(subReference));
                		} else {
                			List<ChailfBankPO> findChailfBankPO = dealDataDao.findChailfBankPO(Long.parseLong(billID));
                			for (ChailfBankPO row : findChailfBankPO) {
                				DBAgent.delete(row);
                			}
                			
                			clBankPO = new ChailfBankPO();
                			
							clBankPO.setId(UUIDLong.longUUID());
							clBankPO.setFormmainId(Long.parseLong(billID));
							clBankPO.setYhkd(String.valueOf(subReference));
							clBankPO.setPzh(voucherId);
                		}
						
						dealDataDao.updateChailfBankPOData(clBankPO);
					} else if ("3".equals(formType)) {
						htBankPO = dealDataDao.findHetongBankPOById(voucherId);
						
						if (htBankPO != null) {
							htBankPO.setYhkd(String.valueOf(subReference));
                		} else {
                			List<HetongBankPO> findHetongBankPO = dealDataDao.findHetongBankPO(Long.parseLong(billID));
                			for (HetongBankPO row : findHetongBankPO) {
                				DBAgent.delete(row);
                			}
                			
                			htBankPO = new HetongBankPO();
                			
							htBankPO.setId(UUIDLong.longUUID());
							htBankPO.setFormmainId(Long.parseLong(billID));
							htBankPO.setYhkd(String.valueOf(subReference));
							htBankPO.setPzh(voucherId);
                		}
						
						dealDataDao.updateHetongBankPOData(htBankPO);
					} else if ("4".equals(formType)) {
						nbzjBankPO = dealDataDao.findNeibuZjBankPOById(voucherId);
						
						if (nbzjBankPO != null) {
							nbzjBankPO.setYhkd(String.valueOf(subReference));
                		} else {
                			List<NeibuZjBankPO> findNeibuZjBankPO = dealDataDao.findNeibuZjBankPO(Long.parseLong(billID));
                			for (NeibuZjBankPO row : findNeibuZjBankPO) {
                				DBAgent.delete(row);
                			}
                			
                			nbzjBankPO = new NeibuZjBankPO();
                			
							nbzjBankPO.setId(UUIDLong.longUUID());
							nbzjBankPO.setFormmainId(Long.parseLong(billID));
							nbzjBankPO.setYhkd(String.valueOf(subReference));
							nbzjBankPO.setPzh(voucherId);
                		}
						
						dealDataDao.updateNeibuZjBankPOData(nbzjBankPO);
					} else if ("5".equals(formType)) {
						fpKjBankPO = dealDataDao.findFapiaoKjBankPOById(voucherId);
						
						if (fpKjBankPO != null) {
							fpKjBankPO.setYhkd(String.valueOf(subReference));
                		} else {
                			List<FapiaoKjBankPO> findFapiaoKjBankPO = dealDataDao.findFapiaoKjBankPO(Long.parseLong(billID));
                			for (FapiaoKjBankPO row : findFapiaoKjBankPO) {
                				DBAgent.delete(row);
                			}
                			
                			fpKjBankPO = new FapiaoKjBankPO();
                			
                			fpKjBankPO.setId(UUIDLong.longUUID());
                			fpKjBankPO.setFormmainId(Long.parseLong(billID));
                			fpKjBankPO.setYhkd(String.valueOf(subReference));
                			fpKjBankPO.setPzh(voucherId);
                		}
						
						dealDataDao.updateFapiaoKjBankPOData(fpKjBankPO);
					} else if ("6".equals(formType)) {
						ZiJinRZPO zjRZPO = dealDataDao.findZiJinRZPOById(Long.parseLong(billID));
						
						zjRZPO.setPzh(voucherId);
						
						dealDataDao.updateZiJinRZPOData(zjRZPO);
					} else if ("7".equals(formType)) {
						FapiaoRzPO fapiaoRzPO = dealDataDao.findFapiaoRzPOById(Long.parseLong(billID));
						
						fapiaoRzPO.setPzh(voucherId);
						
						dealDataDao.updateFapiaoRzPOData(fapiaoRzPO);
					} else {
						log.error("表单类型错误，无法回填数据");
					}
                } else if ("4".equals(from)) {
                	Map<String, Object> map = new HashMap<String, Object>();
            		map.put("appName", "collaboration");
            		Map<String, Object> data1 = new HashMap<String, Object>();
            		data1.put("templateCode", "dzyxTemCode77");
            		data1.put("draft", "0");
            		data1.put("attachments", new ArrayList<Long>());
            		data1.put("relateDoc", "");
            		data1.put("subject", "凭证封面存根");
            		HashMap<String, Object> mainData = new HashMap<String, Object>();
            		Map<String, Object> data = new HashMap<String, Object>();
            		data.put("field0004", subReference);
            		data.put("field0007", voucherId);
            		mainData.put("formmain_5403", data);
            		data1.put("data", mainData);
            		map.put("data", data1);

            		String token;
            		try {
            			token = postToken(userName, password, loginName);
            			String url = restUrl + "/seeyon/rest/bpm/process/start?token=" + token;
            			String result = HttpKit.post(url, JSONUtil.toJSONString(map));
            			try {
            	            JSONObject root = new JSONObject(result);
            	            JSONObject appData = root.getJSONObject("data");

            	            // app_bussiness_data 是转义字符串，需再次解析
            	            String appBusinessDataStr = appData.getString("app_bussiness_data");
            	            JSONObject businessData = new JSONObject(appBusinessDataStr);

            	            summaryId = businessData.getString("summaryId");

            	        } catch (Exception e) {
            	            e.printStackTrace();
            	        }
            		} catch (Exception e) {
            			// TODO Auto-generated catch block
            			e.printStackTrace();
            		}
                }

                List<String> keys = new ArrayList<String>(v3xFiles.keySet());
                List<Attachment> atts = new ArrayList<Attachment>();
                for (String key : keys) {
                    V3XFile file = v3xFiles.get(key);
                    file.setType(type.ordinal());
                    Attachment att = new Attachment(file, category, type);
                    if (StringUtils.isNotBlank(officeMobileAttach) && "enable".equals(officeMobileAttach) && OfficeTransHelper.allowTrans(file)) {
                        att.setOfficeTransformEnable(officeMobileAttach);
                    } else {
                        att.setOfficeTransformEnable("disable");
                    }
                    if (("yes".equals(ucFlag)) && (StringUtils.isNotBlank(reference))) {
                        try {
                            Long referenceLong = Long.valueOf(reference);
                            att.setSubReference(Long.valueOf(type.ordinal()));// 关联保存致信文件的二级关联用于后面的查询
                            att.setReference(referenceLong);
                        } catch (Exception e) {
                            log.error("致信端传入的reference不符合要求", e);
                        }
                    }
                    att.setIdIfNew();
                    if ("1".equals(from)) {
                    	att.setReference(formmain5337.getID());
                    } else if ("2".equals(from)) {
                    	att.setReference(Long.parseLong(billID));
                    } else if ("3".equals(from)) {
                    	ColSummary colSummary = colManager.getColSummaryByFormRecordId(Long.parseLong(billID));
                    	if ("1".equals(formType)) {
                    		att.setReference(colSummary.getId());
    					} else if ("2".equals(formType)) {
    						att.setReference(colSummary.getId());
    					} else if ("3".equals(formType)) {
    						att.setReference(colSummary.getId());
    					} else if ("4".equals(formType)) {
    						att.setReference(colSummary.getId());
    					} else if ("5".equals(formType)) {
    						
    					} else if ("6".equals(formType)) {
    					} else if ("7".equals(formType)) {
    					}
                    } else if ("4".equals(from)) {
                    	att.setReference(Long.parseLong(summaryId));
                    }
                    att.setSubReference(subReference);
                    att.setCategory(66);
                    atts.add(att);
                    getFileManager().save(file);
                }
                
                getAttachmentManager().create(atts);

                return success("添加成功");
            }
            return fail("添加失败");
        } catch (BusinessException e) {
            log.error("", e);
            return fail(e.getMessage());
        } catch (Exception e) {
            log.error("", e);
            return error(e);
        }

    }

    public SystemConfig getSystemConfig() {
        if (systemConfig == null) {
            systemConfig = (SystemConfig) AppContext.getBean("systemConfig");
        }
        return systemConfig;
    }

    public FileManager getFileManager() {
        if (this.fileManager == null) {
            this.fileManager = (FileManager) AppContext.getBean("fileManager");
        }
        return this.fileManager;
    }

    public AttachmentManager getAttachmentManager() {
        if (this.attachmentManager == null) {
            this.attachmentManager = (AttachmentManager) AppContext.getBean("attachmentManager");
        }
        return this.attachmentManager;
    }
    
    /**
	 * 发起流程时需要人员信息的token
	 * 
	 * @param user
	 * @param password
	 * @param loginName
	 * @return
	 * @throws Exception
	 */
	public String postToken(String user, String password, String loginName) throws Exception {
		String url = restUrl + "/seeyon/rest/token/" + user + "/" + password + "?loginName=" + loginName;
		String res = HttpKit.get(url);
		String token = "";
		try {
			token = JsonKit.parse(res).getString("id");
		} catch (Exception e) {
			token = res;
		}
		return token;
	}
}
